<template>
  <div>
    <div class="codeCon" v-if="showCode">
      <img :src="codeImg" alt="" />
      <div>长按图片识别二维码关注亚太天能公众号</div>
    </div>
  </div>
</template>

<script>
import qs from "qs";
import { mapActions } from "vuex";
import { Dialog, Toast } from "vant";
import codeImg from "@/assets/wx/公众号二维码.png";
const BINDDEVICEURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdac90ea64e64dcfc&redirect_uri=http://app.aptenon.com/api/v1/tenon-weixin-h5/gainActivedCode&response_type=code&scope=snsapi_userinfo&state=P002W001#wechat_redirect`;
export default {
  data() {
    return {
      showCode: false,
      codeImg,
    };
  },
  mounted() {
    Toast.loading({
      message: "加载中...",
      forbidClick: true,
    });
    let resQuery = null;
    try {
      resQuery = qs.parse(window.location.href.split("?")[1].split("#")[0]);
    } catch (error) {
      Toast.clear();
      //   Dialog({ message: "获取code失败" });
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdac90ea64e64dcfc&redirect_uri=http%3a%2f%2fapp.aptenon.com%2fcrm%2fh5_web%2factivity.html%23%2fwx%2fsubscribe&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
      return;
    }
    if (resQuery && resQuery.code) {
      this.oauth2getAccessToken(resQuery.code)
        .then((res) => {
          if (res && res.code == "000000" && res.data) {
            let WxOpenId = res.data.openId;
            return this.getWxUserData({
              openid: WxOpenId,
            });
          } else {
            return null;
          }
        })
        .then((res) => {
          Toast.clear();
          if (res && res.code == 0) {
            if (res.subscribe) {
              window.location.href = BINDDEVICEURL;
            } else {
              this.showCode = true;
              Dialog({ message: "请先关注公众号再进行设备绑定" });
            }
          } else {
            Dialog({ message: "获取订阅信息失败" });
          }
        })
        .catch((err) => {
          Toast.clear();
          Dialog({ message: "网络错误" });
        });
    } else {
      Toast.clear();
      Dialog({ message: "获取code失败" });
    }
  },
  methods: {
    ...mapActions({
      getWxUserData: "user/getWxUserData",
      oauth2getAccessToken: "user/oauth2getAccessToken",
    }),
  },
};
</script>

<style lang="scss" scoped>
.codeCon {
  text-align: center;
  padding: 24px;
}
</style>